package nl.walnut.ileftyousomecheddar;

import java.io.IOException;
import java.io.StringReader;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.Bundle;
//import android.os.StrictMode;
//import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

public class MainActivity extends Activity {

	// The screen is divided in 9 cells, to represent a compass. The numbers for
	// the cell is down here.
	private static final int ORIGIN = 0;
	private static final int ONE_THIRD_WIDTH = 127;
	private static final int TWO_THIRD_WIDTH = 254;
	private static final int ENTIRE_WIDTH = 480;
	private static final int ONE_THIRD_HEIGHT = 183;
	private static final int TWO_THIRD_HEIGHT = 366;
	private static final int ENTIRE_HEIGHT = 800;
	private static final int LAYOUT_UNDER = 40;
	private static final int BUTTON_WIDTH = 70;
	private static final int BUTTON_HEIGHT = 20;

	protected LocationManager locationManager;
	Location location;
	Button cheesebt[] = new Button[10];
	Cheese cheese[] = new Cheese[10];
	int number = 0; // cheese number

	private Location getLocation() throws Exception {
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
		/* MINIMUM_TIME_BETWEEN_UPDATES */10000,
		/* MINIMUM_DISTANCE_CHANGE_FOR_UPDATES */2, new MyLocationListener());
		
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
				/* MINIMUM_TIME_BETWEEN_UPDATES */10000,
				/* MINIMUM_DISTANCE_CHANGE_FOR_UPDATES */2, new MyLocationListener());
		
		
		location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if(location == null){
			location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		}
		if(location == null){
			throw new Exception("can not aquire location");
		}
		return location;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		/*
		 * Display display = getWindowManager().getDefaultDisplay(); Point size
		 * = new Point(); display.getSize(size); int width = size.x; int height
		 * = size.y; System.out.println("width:"+width);
		 * System.out.println("height:"+height);
		 */
		
		Button bt = (Button) findViewById(R.id.leaveCheese);
		bt.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(v.getContext(), WriteCheeseActivity.class);
				v.getContext().startActivity(i);
			}
		});
		
		try{
		location = this.getLocation();

		/*
		 * bt= (Button) findViewById(R.id.grateCheese);
		 * bt.setOnClickListener(new View.OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { Intent i=new
		 * Intent(v.getContext(), GrateCheeseActivity.class);
		 * v.getContext().startActivity(i);} });
		 */

		// StrictMode.ThreadPolicy policy = new
		// StrictMode.ThreadPolicy.Builder().permitAll().build();
		// StrictMode.setThreadPolicy(policy);

		HttpClient httpClient = new DefaultHttpClient();
		String ht = "http://digital-notes.appspot.com/digital_notes?lng=" + location.getLongitude() + "&lat=" + location.getLatitude();
		// System.out.println(ht);
		HttpGet httpGet = new HttpGet(ht);
		try {
			HttpResponse urlResponse = httpClient.execute(httpGet);
			try {
				createCheese(EntityUtils.toString(urlResponse.getEntity()));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}catch(Exception e){
			Log.e(ACTIVITY_SERVICE,e.getMessage());
			Toast.makeText(MainActivity.this, "Can not aquire your position",Toast.LENGTH_LONG).show();
		}

		createButtons();

	}

	public void onSaveInstanceState() {
	}

	public void leaveCheese(View view) {
		// Button bt= (Button) findViewById(R.id.addCheddar);
		// Intent i=new Intent(view.getContext(), WriteCheeseActivity.class);
		// view.getContext().startActivity(i);
		
		AbsoluteLayout al = (AbsoluteLayout) findViewById(R.id.al);

		if (number < 10) { // only 10 cheese on screen
			Button nb = new Button(this);
			nb.setText("500 m");
			nb.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent i = new Intent(v.getContext(), CheddarActivity.class);
					v.getContext().startActivity(i);
				}
			});

			// api 11
			// nb.setX(60);
			// nb.setY(90);
			
			// api 7
			AbsoluteLayout.LayoutParams absParams = (AbsoluteLayout.LayoutParams)nb.getLayoutParams();
			absParams.x = 60;
			absParams.y = 90;
			nb.setLayoutParams(absParams);
			
			nb.setBackgroundColor(getResources().getColor(R.color.cheddar));
			//RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);

			al.addView(nb);

			Random r = new Random();

			int x = r.nextInt(127);
			int y = r.nextInt(183);

			// api 11s
			// nb.setX(x);
			// nb.setY(y);
			
			// api 7
			AbsoluteLayout.LayoutParams absParams2 = (AbsoluteLayout.LayoutParams)nb.getLayoutParams();
			absParams2.x = x;
			absParams2.y = y;
			nb.setLayoutParams(absParams2);

			cheesebt[number] = nb;
			number++;
		} else {
			Toast.makeText(MainActivity.this, "No more cheese can be left", Toast.LENGTH_LONG).show();
		}
	}

	protected void showCurrentLocation() {

		location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

		if (location != null) {
			String message = String.format("Current Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude());
			Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location loc) {
			location = loc;
			redraw();
			// String message = String.format(
			// "New Location \n Longitude: %1$s \n Latitude: %2$s",
			// loc.getLongitude(), loc.getLatitude()
			// );
			// Toast.makeText(MainActivity.this, message,
			// Toast.LENGTH_LONG).show();
		}

		public void onStatusChanged(String s, int i, Bundle b) {
			// Toast.makeText(MainActivity.this, "Provider status changed",
			// Toast.LENGTH_LONG).show();
		}

		public void onProviderDisabled(String s) {
			// Toast.makeText(MainActivity.this,
			// "Provider disabled by the user. GPS turned off",
			// Toast.LENGTH_LONG).show();
		}

		public void onProviderEnabled(String s) {
			// Toast.makeText(MainActivity.this,
			// "Provider enabled by the user. GPS turned on",
			// Toast.LENGTH_LONG).show();
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void redraw() {

		RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
		AbsoluteLayout al = (AbsoluteLayout) findViewById(R.id.al);
		for (int j = 0; j < number; j++) {
			al.removeView(cheesebt[j]);
		}
		number = 0;
		HttpClient httpClient = new DefaultHttpClient();
		String ht = "http://digital-notes.appspot.com/digital_notes?lng=" + location.getLongitude() + "&lat=" + location.getLatitude();
		HttpGet httpGet = new HttpGet(ht);
		try {
			HttpResponse urlResponse = httpClient.execute(httpGet);
			try {
				createCheese(EntityUtils.toString(urlResponse.getEntity()));
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		createButtons();
		findViewById(R.id.rl).invalidate();

	}

	public void createButtons() {

		Button nb;
		String dir;
		int dis, x, y;
		RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
		AbsoluteLayout al = (AbsoluteLayout) findViewById(R.id.al);

		for (int j = 0; j < number; j++) {
			dir = cheese[j].getDirection();
			dis = cheese[j].getDistance();
			nb = new Button(this);

			cheesebt[j] = nb;
			nb.setText(dis + " m " + dir);
			/*
			 * nb.setOnClickListener(new View.OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { Intent i=new
			 * Intent(v.getContext(), CheddarActivity.class);
			 * v.getContext().startActivity(i);} });
			 */
			nb.setBackgroundColor(getResources().getColor(R.color.cheddar));

			al.addView(nb);

			// Random r = new Random();
			x = ENTIRE_WIDTH / 2 - BUTTON_WIDTH;
			y = (ENTIRE_HEIGHT - LAYOUT_UNDER) / 2 - BUTTON_HEIGHT;

			/*
			 * if(cheese[j].getDistance()< 5){ x += ONE_THIRD_WIDTH; y +=
			 * ONE_THIRD_HEIGHT; } else{
			 */
			if (dir.equals("NW")) {
				x -= dis /* ORIGIN */;
				y -= dis /* ORIGIN */;
			}
			if (dir.equals("N")) {
				// x += ONE_THIRD_WIDTH;
				y -= dis /* ORIGIN */;
			}
			if (dir.equals("NE")) {
				x += dis /* TWO_THIRD_WIDTH */;
				y -= dis /* ORIGIN */;
			}
			if (dir.equals("W")) {
				x -= dis /* ORIGIN */;
				/* y += ONE_THIRD_HEIGHT; */}
			if (dir.equals("E")) {
				x += dis /* TWO_THIRD_WIDTH */;
				/* y += ONE_THIRD_HEIGHT; */}
			if (dir.equals("SW")) {
				x -= dis /* ORIGIN */;
				y += dis /* TWO_THIRD_HEIGHT */;
			}
			if (dir.equals("S")) {
				// x += ONE_THIRD_WIDTH;
				y += dis /* TWO_THIRD_HEIGHT */;
			}
			if (dir.equals("SE")) {
				x += dis /* TWO_THIRD_WIDTH */;
				y += dis /* TWO_THIRD_HEIGHT */;
			}
			// }

			if (x < 0)
				x = 0;
			else if (x > ENTIRE_WIDTH)
				x = ENTIRE_WIDTH;
			if (y < 0)
				y = 0;
			else if (y > (ENTIRE_WIDTH - LAYOUT_UNDER))
				y = ENTIRE_WIDTH - LAYOUT_UNDER;

			// api 11
			// nb.setX(x);
			// nb.setY(y);
			
			// api 7
			//nb.setLayoutParams(new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.FILL_PARENT, AbsoluteLayout.LayoutParams,x, y));
			AbsoluteLayout.LayoutParams absParams = (AbsoluteLayout.LayoutParams)nb.getLayoutParams();
			absParams.x = x;
			absParams.y = y;
			nb.setLayoutParams(absParams);
			
			if (cheese[j].getDistance() < 2) {
				final int index = j;
				nb.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent i = new Intent(v.getContext(), CheddarActivity.class);
						i.putExtra("nl.walnut.ileftyousomecheddar.title", cheese[index].getTitle());
						i.putExtra("nl.walnut.ileftyousomecheddar.text", cheese[index].getText());
						v.getContext().startActivity(i);
					}

				});
			} else {
				nb.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Toast.makeText(MainActivity.this, "You are too far to read this, even with glasses.", Toast.LENGTH_LONG).show();

					}
				});
			}
		}
	}

	public void createCheese(String doc) throws XmlPullParserException, IOException {

		int dis = 0;
		String tit = null, tex = null, dir = null, id = null;

		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();

		xpp.setInput(new StringReader(doc));
		int eventType = xpp.getEventType();
		while (eventType != XmlPullParser.END_DOCUMENT && number < 10) {
			if (eventType == XmlPullParser.START_TAG) {
				String name = xpp.getName();
				if (name.equals("id")) {
					xpp.next();
					id = xpp.getText();
					// System.out.println(number + "id");
				}
				if (name.equals("title")) {
					xpp.next();
					tit = xpp.getText();
					// System.out.println(number + "title");
				}
				if (name.equals("text")) {
					xpp.next();
					tex = xpp.getText();
					// System.out.println(number + "text");
				}
				if (name.equals("distance")) {
					xpp.next();
					dis = (int) Double.parseDouble(xpp.getText());
					// System.out.println(number + "distance");
				}
				if (name.equals("cardinalDirection")) {
					xpp.next();
					dir = xpp.getText();
					// System.out.println(number + "direction");
					cheese[number] = new Cheese(id, dis, tit, tex, dir);
					number++;
				}

			} else if (eventType == XmlPullParser.END_TAG) {
				// System.out.println("End tag "+xpp.getName());
			} else if (eventType == XmlPullParser.TEXT) {
				// System.out.println("Text "+xpp.getText());
			}
			eventType = xpp.next();

		}

	}

}
/*
 * QUESTO È PER QUANDO VIENE GIRATO LO SMARTPHONE. NON SONO SICURO FUNZIONI
 * PERCHÉ NON HO POSSIBILITÀ DI GIRARE SMARTPHONE...
 * 
 * CAMPI DELL'ACTIVITY protected Sensor sensor; protected SensorManager
 * sensorService;
 * 
 * 
 * QUESTA PARTE VA IN ONCREATE sensorService = (SensorManager)
 * getSystemService(Context.SENSOR_SERVICE); sensor =
 * sensorService.getDefaultSensor(Sensor.TYPE_ORIENTATION); if (sensor != null)
 * { sensorService.registerListener(mySensorEventListener, sensor,
 * SensorManager.SENSOR_DELAY_NORMAL); Log.i("Compass MainActivity",
 * "Registerered for ORIENTATION Sensor");
 * 
 * } else { Log.e("Compass MainActivity",
 * "Registerered for ORIENTATION Sensor"); Toast.makeText(this,
 * "ORIENTATION Sensor not found", Toast.LENGTH_LONG).show(); finish(); }
 * 
 * IN ONDESTROY if (sensor != null) {
 * sensorService.unregisterListener(mySensorEventListener); }
 * 
 * METODO DELL'ACTIVITY private SensorEventListener mySensorEventListener = new
 * SensorEventListener() {
 * 
 * @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { }
 * 
 * @Override public void onSensorChanged(SensorEvent event) { // angle between
 * the magnetic north directio // 0=North, 90=East, 180=South, 270=West
 * Toast.makeText(MainActivity.this, "Telefono girato di " + event.values[0] +
 * " gradi", Toast.LENGTH_LONG).show(); } };
 * 
 * Random r=new Random();
 * 
 * for(int j=0; j<10; j++){ int dis=r.nextInt(500); String tit="Title " + j;
 * String tex="Text " + j; String dir; switch(r.nextInt(7)){ case 0: dir="N";
 * break; case 1: dir="NE"; break; case 2: dir="E"; break; case 3: dir="SE";
 * break; case 4: dir="S"; break; case 5: dir="SW"; break; case 6: dir="W";
 * break; case 7: dir="NW"; break; default: dir="N"; break; }
 * 
 * 
 * }
 */